package io.renren.modules.doc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.doc.dao.ChatHistoryDao;
import io.renren.modules.doc.entity.ChatHistoryEntity;
import io.renren.modules.doc.service.ChatHistoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("chatHistoryService")
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryDao, ChatHistoryEntity> implements ChatHistoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String sessionId = (String)params.get("sessionId");
        String keyword = (String)params.get("keyword");

        QueryWrapper<ChatHistoryEntity> queryWrapper = new QueryWrapper<ChatHistoryEntity>();
        if(StringUtils.isNotBlank(sessionId)){
            queryWrapper.eq("session_id", sessionId);
        }
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.like("message", keyword);
        }
        queryWrapper.orderByDesc("create_time");

        IPage<ChatHistoryEntity> page = this.page(
                new Query<ChatHistoryEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveChatHistory(ChatHistoryEntity chatHistory) {
        if (chatHistory == null) {
            return;
        }
        Date now = new Date();
        chatHistory.setCreateTime(now);
        chatHistory.setUpdateTime(now);
        this.save(chatHistory);
    }

    @Override
    public List<ChatHistoryEntity> getSessionHistory(String sessionId) {
        if (StringUtils.isBlank(sessionId)) {
            return null;
        }
        return baseMapper.getChatHistoryBySessionId(sessionId);
    }

    @Override
    public List<ChatHistoryEntity> findSimilarChats(Double[] vectorEmbedding, double threshold, int limit) {
        if (vectorEmbedding == null || vectorEmbedding.length == 0) {
            return null;
        }
        return baseMapper.findSimilarChats(vectorEmbedding, threshold, limit);
    }

    @Override
    public List<Map<String, Object>> getUserSessions(Long userId) {
        if (userId == null || userId <= 0) {
            return null;
        }
        return baseMapper.getUserSessions(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void renameSession(String sessionId, String title) {
        if (StringUtils.isBlank(sessionId) || StringUtils.isBlank(title)) {
            return;
        }
        ChatHistoryEntity chatHistory = new ChatHistoryEntity();
        chatHistory.setSessionId(sessionId);
        chatHistory.setTitle(title);
        chatHistory.setUpdateTime(new Date());
        
        QueryWrapper<ChatHistoryEntity> queryWrapper = new QueryWrapper<ChatHistoryEntity>()
            .eq("session_id", sessionId);
        this.update(chatHistory, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSession(String sessionId) {
        if(StringUtils.isBlank(sessionId)){
            return;
        }
        QueryWrapper<ChatHistoryEntity> queryWrapper = new QueryWrapper<ChatHistoryEntity>()
            .eq("session_id", sessionId);
        this.remove(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVectorEmbedding(Long id, Double[] vectorEmbedding) {
        if(id == null || id <= 0 || vectorEmbedding == null || vectorEmbedding.length == 0){
            return;
        }
        ChatHistoryEntity chatHistory = new ChatHistoryEntity();
        chatHistory.setId(id);
        chatHistory.setVectorEmbedding(vectorEmbedding);
        chatHistory.setUpdateTime(new Date());
        this.updateById(chatHistory);
    }
}
